<template>
  <div class="flex items-center w-full px-0 mt-4 select-none">
    <slot name="left"></slot>
    <div v-if="batch" class="flex items-center gap-x-4">
      <el-checkbox
        :model-value="!!check"
        :indeterminate="indeterminate"
        @update:model-value="emit('update:check', !!$event)"
      />
      <el-button
        :disabled="batchButtonDisabled"
        class="ml-4"
        @click="emit('batch')"
      >
        {{ batchButtonText }}
      </el-button>
    </div>
    <el-pagination
      v-model:current-page="state.page"
      v-model:page-size="state.limit"
      :page-sizes="pageSizes"
      :disabled="disabled"
      :background="background"
      :class="`align-${align}`"
      layout="total,prev,pager,next,sizes"
      :total="state.total ? Number(state.total) : 0"
      @current-change="handlePaginationChange()"
      @size-change="handlePaginationChange(true)"
    />
  </div>
</template>

<script setup lang="ts">
import { pageSizes } from '@/config'

interface IProps {
  check?: boolean
  indeterminate?: boolean
  batch?: boolean
  pagination: PaginationState
  border?: boolean
  align?: 'right' | 'left' | 'between'
  disabled?: boolean
  background?: boolean
  batchButtonDisabled?: boolean
  batchButtonText?: string
}
const props = withDefaults(defineProps<IProps>(), {
  border: false,
  disabled: false,
  background: false,
  align: 'right',
  batchButtonDisabled: false,
  batchButtonText: '批量删除'
})

interface IEmit {
  (event: 'batch'): void
  (event: 'change', pagination?: PaginationState): void
  (event: 'update:check', value: boolean): void
}
const emit = defineEmits<IEmit>()

const state = computed(() => props.pagination)

const handlePaginationChange = (resetPage: boolean = false) => {
  if (resetPage) state.value.page = 1

  const { page, limit } = state.value
  state.value.offset = (page - 1) * limit

  emit('change', state.value)
}

defineExpose({
  reset() {
    state.value.page = 1
    state.value.limit = 20
    state.value.offset = 0
    handlePaginationChange()
  }
})
</script>

<style scoped lang="scss">
:deep(.el-pagination) {
  &[class*='align'] {
    @apply w-full;
  }
  @apply text-xs text-[#83858A];
  &.align-between {
    .el-pagination__jump {
      // @apply ml-auto;
    }

    .btn-prev {
      @apply ml-auto;
    }
  }

  &.align-right {
    @apply ml-auto w-auto;
  }

  .el-pagination__total {
    color: #868d9d;
  }
  .el-pagination__sizes > .el-select {
    @apply w-[100px];
  }
  .btn-prev {
    @apply rounded;
  }

  .btn-next {
    @apply rounded;
  }
  .el-pager {
    @apply text-[#83858A] mx-1;
    .number {
      @apply rounded;
    }

    .number:not(:last-child) {
      margin-right: 4px;
    }

    .is-active {
      background-color: #e8f3ff;
    }
  }
  .el-pagination__jump {
    @apply text-[#83858A];
  }
}
</style>
